﻿CREATE PROCEDURE [maint].[CheckErrorStatus]
@DbName [sysname], @Action CHAR (1)
AS
BEGIN
	DECLARE @RC INT;
	SET @RC = 0;
	
	DECLARE @ErrorStatus INT, @ErrorMessage NVARCHAR(255);
	
	SELECT
		@ErrorStatus = [ErrorStatus]
		,@ErrorMessage = CASE
			WHEN ([ErrorStatus] & 1 <> 0) AND (@Action = 'I') THEN 'The last index defragmentation failed for database %s.'
			WHEN ([ErrorStatus] & 2 <> 0) AND (@Action = 'S') THEN 'The last statistics update failed for database %s.'
			WHEN ([ErrorStatus] & 4 <> 0) AND (@Action = 'C') THEN 'The last consistancy check failed for database %s.'
		END
	FROM [config].[DbMaintenance]
	WHERE ([DbName] = @DbName);
	
	IF(@ErrorMessage IS NOT NULL)
	BEGIN
		RAISERROR(@ErrorMessage,16,1,@DbName);
		SET @RC = @ErrorStatus;
	END;
	
	RETURN(@RC);
END